// 任务管理功能
document.addEventListener('DOMContentLoaded', function() {
    const taskForm = document.getElementById('task-form');
    const taskList = document.getElementById('task-list');
    
    // 从localStorage加载任务
    loadTasks();
    
    // 添加任务表单提交事件
    taskForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const title = document.getElementById('task-title').value;
        const description = document.getElementById('task-description').value;
        const dueDate = document.getElementById('task-due-date').value;
        
        if (title.trim() === '') {
            alert('请输入任务标题');
            return;
        }
        
        addTask(title, description, dueDate);
        taskForm.reset();
    });
    
    // 添加任务函数
    function addTask(title, description, dueDate) {
        const task = {
            id: Date.now(),
            title,
            description,
            dueDate,
            completed: false,
            createdAt: new Date().toISOString()
        };
        
        let tasks = getTasks();
        tasks.push(task);
        saveTasks(tasks);
        renderTasks();
    }
    
    // 完成任务函数
    function completeTask(id) {
        let tasks = getTasks();
        tasks = tasks.map(task => {
            if (task.id === id) {
                task.completed = !task.completed;
            }
            return task;
        });
        saveTasks(tasks);
        renderTasks();
    }
    
    // 编辑任务函数
    function editTask(id) {
        let tasks = getTasks();
        const task = tasks.find(task => task.id === id);
        
        if (task) {
            const newTitle = prompt('编辑任务标题', task.title);
            if (newTitle === null) return; // 用户取消了编辑
            
            const newDescription = prompt('编辑任务描述', task.description);
            const newDueDate = prompt('编辑截止日期 (YYYY-MM-DD)', task.dueDate);
            
            if (newTitle.trim() === '') {
                alert('任务标题不能为空');
                return;
            }
            
            tasks = tasks.map(t => {
                if (t.id === id) {
                    t.title = newTitle;
                    t.description = newDescription;
                    t.dueDate = newDueDate;
                }
                return t;
            });
            
            saveTasks(tasks);
            renderTasks();
        }
    }
    
    // 删除任务函数
    function deleteTask(id) {
        if (confirm('确定要删除这个任务吗？')) {
            let tasks = getTasks();
            tasks = tasks.filter(task => task.id !== id);
            saveTasks(tasks);
            renderTasks();
        }
    }
    
    // 从localStorage获取任务
    function getTasks() {
        const tasksJSON = localStorage.getItem('tasks');
        return tasksJSON ? JSON.parse(tasksJSON) : [];
    }
    
    // 保存任务到localStorage
    function saveTasks(tasks) {
        localStorage.setItem('tasks', JSON.stringify(tasks));
    }
    
    // 加载任务
    function loadTasks() {
        renderTasks();
    }
    
    // 渲染任务列表
    function renderTasks() {
        const tasks = getTasks();
        
        if (tasks.length === 0) {
            taskList.innerHTML = `
                <div class="empty-state">
                    <h2>还没有任务</h2>
                    <p>添加新任务开始管理您的待办事项</p>
                </div>
            `;
            return;
        }
        
        taskList.innerHTML = '';
        
        tasks.forEach(task => {
            const taskElement = document.createElement('div');
            taskElement.className = `task-card ${task.completed ? 'completed' : ''}`;
            taskElement.innerHTML = `
                <div class="task-title">${escapeHtml(task.title)}</div>
                <div class="task-description">${escapeHtml(task.description || '无描述')}</div>
                <div class="task-due-date">截止日期: ${task.dueDate || '无'}</div>
                <div class="task-actions">
                    <button class="btn-complete">${task.completed ? '标记未完成' : '标记完成'}</button>
                    <button class="btn-edit">编辑</button>
                    <button class="btn-delete">删除</button>
                </div>
            `;
            
            // 添加事件监听器
            taskElement.querySelector('.btn-complete').addEventListener('click', () => completeTask(task.id));
            taskElement.querySelector('.btn-edit').addEventListener('click', () => editTask(task.id));
            taskElement.querySelector('.btn-delete').addEventListener('click', () => deleteTask(task.id));
            
            taskList.appendChild(taskElement);
        });
    }
    
    // 防止XSS攻击的简单转义函数
    function escapeHtml(unsafe) {
        if (!unsafe) return '';
        return unsafe
            .toString()
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }
});